<template>
    <div class="car-dynamic-list" style=" position: relative;">

        <div>
            <span style="font-weight:700;color:#3a71a8;font-size:20px;margin-right:10px">24小时动态列表</span>
            <el-date-picker v-model="find_data.stime" type="date" placeholder="查询日期" style="width: 130px"
                value-format="YYYY-MM-DD" format="YYYY-MM-DD">
            </el-date-picker>



            <el-input clearable style="width: 130px;margin-left:10px;" placeholder="需求座位数" maxlength="5"
                onkeyup="this.value = this.value.replace(/^(0+)|[^\d]+/g, '');" v-model="find_data.seats">
            </el-input>

            <el-input clearable style="width: 130px;margin-left:10px;" placeholder="停靠点名称" maxlength="20"
                v-model="find_data.simpleDockedAddress">
            </el-input>

            <el-select v-model="find_data.serviceType" :placeholder="'可跑区域'" style="width: 150px;margin-left:10px;">
                <el-option label="可跑区域（全部）" value=""></el-option>
                <el-option label="县际业务" value="COUNTY_SER"></el-option>
                <el-option label="市际业务" value="CITY_SER"></el-option>
                <el-option label="省际业务" value="PROVINCE_SER"></el-option>
            </el-select>

            <el-select clearable v-model="find_data.plateNum" :placeholder="'全部车牌号'"
                style="width: 150px;margin-left:10px;">
                <el-option v-for="item in carNumList" :key="item.id" :label="item.plate_num" :value="item.plate_num">
                </el-option>
            </el-select>

            <el-select v-model="find_data.haveRoute" :placeholder="'有无行程'" style="width: 150px;margin-left:10px;">
                <el-option label="有无行程" :value="''"></el-option>
                <el-option label="有" :value="'1'"></el-option>
                <el-option label="无" :value="'0'"></el-option>
            </el-select>

            <!-- <el-select v-model="find_data.dataType" :placeholder="'数据类型'" style="width: 130px;margin-left:10px;"
                    @change="selDataType">
                    <el-option :label="'按24小时展示'" :value="'1'"></el-option>
                    <el-option :label="'按30天展示'" :value="'2'"></el-option>
                </el-select> -->

            <el-select multiple collapse-tags clearable v-model="companyNums" :placeholder="'托管单位名称'"
                style="width: 150px;margin-left:10px;">
                <template #header>
                    <el-checkbox v-model="checkAll" :indeterminate="indeterminate" @change="handleCheckAll">
                        全选
                    </el-checkbox>
                </template>
                <el-option v-for="item in findTrusteeshipMeComboList" :key="item.id" :label="item.companyName"
                    :value="item.companyNum">
                </el-option>
            </el-select>

            <template v-if="find_data.dataType == '1'">
                <el-button style="margin-left:10px;" type="primary" icon="DArrowLeft" title="上一天"
                    @click="get24DgList('1')"></el-button>
                <el-button type="primary" icon="Search" @click="get24DgList('0')">今天</el-button>
                <el-button type="primary" icon="DArrowRight" title="下一天" @click="get24DgList('2')"></el-button>
            </template>

            <el-button style="margin-left: 20px;height:30px" @click="search_btn" type="primary"
                icon="Search">搜索</el-button>
        </div>

        <div style="margin: 10px 0px;" class="car-list">
            <template v-if="find_data.dataType == 1">
                <span v-if="!list24" class="c-gray">没有空车数据！</span>
                <template v-else>
                    <ul style="height:28px">
                        <li>
                            <label><span>车牌号 / 座位数</span></label>
                            <label><span>师傅姓名</span></label>
                            <label class="lab-24"><span>停靠点</span><u>0</u></label>
                            <label class="lab-24" v-for="h in 24" :key="h">
                                <u v-if="h < 10">0{{ h }}</u>
                                <u v-else>{{ h }}</u>
                            </label>
                        </li>
                    </ul>
                    <ul :style="{ 'height': height_num, }" style="overflow: hidden;" class="hovercss">
                        <li v-for="(it, i) in list24" :key="i">
                            <label :title="'编号 ' + (i + 1)"><span>{{ it.plateNum }} / <b>{{ it.seats
                                        }}</b></span></label>
                            <label><span :class="{ 'c-gray': it.driverInfo == '无主驾' ? true : false }">{{
                                it.driverInfo.split('/')[0]
                                    }}</span></label>
                            <label>
                                <el-tooltip placement="top">
                                    <template #content>{{ it.address }}</template>
                                    <span>{{ it.address }}</span>
                                </el-tooltip>
                            </label>
                            <label style="margin-left: -0.4px;" class="lab-24" v-for="h in 24" :key="h"></label>

                            <template v-if="it.orders">

                                <i v-for="(r, index) in it.orders" :key="'_' + index"
                                    :style="{ 'left': r.left, 'width': r.width, 'background': (index + 1) % 2 == 0 ? '#91cc75' : '#5470c6' }">
                                    <el-tooltip placement="top" :popper-class="'route-tips'">
                                        <template #content>
                                            {{ r.tips }}
                                        </template>
                                        <span>{{ r.tips }}</span>
                                    </el-tooltip>


                                </i>
                            </template>


                        </li>

                    </ul>
                </template>
            </template>

            <template v-else>
                <span v-if="!list30" class="c-gray">没有空车数据！</span>
                <template v-else>
                    <ul style="height:28px">
                        <li>
                            <label><span>车牌号 / 座位数</span></label>
                            <label><span>师傅姓名</span></label>
                            <label><span>师傅手机</span></label>
                            <label class="lab-30" v-for="h in 30" :key="h">
                                <u v-if="h < 10">0{{ h }}</u>
                                <u v-else>{{ h }}</u>
                            </label>
                        </li>
                    </ul>
                    <ul style="height:70vh;overflow: hidden;" class="hovercss">
                        <li v-for="(it, i) in list30" :key="i">
                            <label><span>{{ it.carMap.plateNum }} / <b>{{ it.carMap.seats }}</b></span></label>
                            <label><span :class="{ 'c-gray': it.carMap.driverInfo == '无主驾' ? true : false }">{{
                                it.carMap.driverInfo.split('/')[0] }}</span></label>
                            <label>
                                <span>{{ it.carMap.driverInfo.split('/')[1] }}</span>
                            </label>
                            <label style="margin-left: -0.36px;" class="lab-30" v-for="(h, index5) in 30" :key="h">
                                <!-- <span v-if="it.carMap.ds[h]" :title="it.carMap.ds[h]">{{it.carMap.ds[h]}}</span> -->
                                <!-- <i v-for="(r, index) in it.orders" :key="'_' + index"
                                    :style="{ 'left': r.left, 'width': r.width, 'background': (index + 1) % 2 == 0 ? '#91cc75' : '#5470c6' }">
                                    <el-tooltip placement="top" :popper-class="'route-tips'">
                                        <template #content>
                                            {{ r.tips }}
                                        </template>
    <span>{{ r.tips }}</span>
    </el-tooltip>

    </i> -->
                                <template v-if="it.carMap.ds[h]">

                                    <!-- <el-tooltip v-if="it.carMap.ds[h].length > 3" placement="top">
                                        <template #content>{{ it.carMap.ds[h] }}</template>
    <span>{{ it.carMap.ds[h] }}</span>
    </el-tooltip>
    <template v-else>{{ it.carMap.ds[h] }}</template> -->
                                    <div style='  
                                        width: 100px;
                                        height: 100px;
                                        font-weight: 700;
                                        color:#fff'
                                        :style="{ 'background': (index5 + 1) % 2 == 0 ? 'red' : 'rgb(191 165 40)' }">

                                        <el-tooltip placement="top">
                                            <template #content>{{ Number(it.carMap.ds[h]) ? it.carMap.ds[h] + '单' :
                                                it.carMap.ds[h]
                                                }}</template>
                                            <span>{{ Number(it.carMap.ds[h]) ? it.carMap.ds[h] + '单' :
                                                it.carMap.ds[h]
                                                }}</span>
                                        </el-tooltip>
                                    </div>


                                </template>
                            </label>
                        </li>
                    </ul>
                </template>
            </template>
        </div>
    </div>

    <!-- 弹窗 -->
    <div>


    </div>
</template>

<script setup>
import Sortable from 'sortablejs';
import { GET_TOKEN } from '@/utils/token.js'
import { watch, ref, reactive, onMounted, computed } from 'vue'
import {
    adupPrivateSet, getPrivateSetList, carScheduleList, carServiceList, findCarCombo, findTrusteeshipMeCombo

} from '@/api/information_center.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import { importCusCheckInData } from '@/utils/common.js'
import CircularJSON from 'circular-json'
onMounted(async () => {
    // let account_management = JSON.parse(localStorage.getItem('account_management'))
    // if (account_management) {
    //     find_data.find = account_management.find
    // }






    findTrusteeshipMeCombo({
        page: {
            pageNum: 1,
            pageSize: 999,
        },
        companyName: '',
    }).then(res => {
        findTrusteeshipMeComboList.value = res.data || [];
        for (let i = 0; i < findTrusteeshipMeComboList.value.length; i++) {
            companyNums.value.push(findTrusteeshipMeComboList.value[i].companyNum)
        }
        checkAll.value = true

        findCarCombo({
            page: {
                pageNum: 1,
                pageSize: 999,
            },
            plateNum: '',
            companyNums: companyNums.value,
        }).then(res => {
            carNumList.value = res.data.list || [];
            list_api();
        })
    })



    new_data()

    // let luser = JSON.parse(localStorage.getItem("luser"))
    // let luser_companyNum = luser.companyNum
    // companyNums.value = [luser_companyNum]



})

const checkAll = ref(false)
const indeterminate = ref(false)
const findTrusteeshipMeComboList = ref([])
const companyNums = ref([])
watch(companyNums, (val) => {

    if (val.length === 0) {
        checkAll.value = false
        indeterminate.value = false
    } else if (val.length === findTrusteeshipMeComboList.value.length) {
        checkAll.value = true
        indeterminate.value = false
    } else {
        indeterminate.value = true
    }
})
const height_num = ref('')
const handleCheckAll = (val) => {
    indeterminate.value = false
    if (val) {
        companyNums.value = findTrusteeshipMeComboList.value.map((_) => _.companyNum)
    } else {
        companyNums.value = []
    }

}
//#region 分页列表
// 获取当前的年月日
const new_data = () => {
    let currentDate = new Date();

    let year = currentDate.getFullYear();
    let month = String(currentDate.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需要加一
    let day = String(currentDate.getDate()).padStart(2, '0');

    let formattedDate = `${year}-${month}-${day}`;
    return formattedDate

}
const to_data = () => {
    let currentDate = new Date(find_data.stime);
    let pastDate = new Date(currentDate.getTime() - 24 * 60 * 60 * 1000); // 24小时前的时间

    let year = pastDate.getFullYear();
    let month = String(pastDate.getMonth() + 1).padStart(2, '0');
    let day = String(pastDate.getDate()).padStart(2, '0');

    let formattedDate = `${year}-${month}-${day}`;
    return formattedDate
}
const go_data = () => {
    let currentDate = new Date(find_data.stime);
    let pastDate = new Date(currentDate.getTime() + 24 * 60 * 60 * 1000); // 24小时前的时间

    let year = pastDate.getFullYear();
    let month = String(pastDate.getMonth() + 1).padStart(2, '0');
    let day = String(pastDate.getDate()).padStart(2, '0');

    let formattedDate = `${year}-${month}-${day}`;
    return formattedDate
}
const num_value = ref(0)
const get24DgList = (e) => {
    if (e == 0) {
        num_value.value = 0
        find_data.stime = new_data()
        list_api()
    } else if (e == 1) {
        num_value.value = num_value.value - 1
        find_data.stime = to_data()
        list_api()
    } else if (e == 2) {
        num_value.value = num_value.value + 1
        find_data.stime = go_data()
        list_api()
    }
}
const selDataType = () => {
    list_api()
}
const carNumList = ref([])
const list_data = ref([])
const list24 = ref([])
const list30 = ref([])
const find_data = reactive({
    page: {
        pageNum: 1,
        pageSize: 20,
    },
    haveRoute: '',
    plateNum: '',
    seats: '',
    serviceType: '',
    simpleDockedAddress: '',
    stime: new_data(),
    whichDay: '',
    dataType: '1',
    companyNums: [],
})


// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    find_data.page.pageNum = 1
    list_api()
}

// 分页器跳转页面
const current_change_btn = () => {
    list_api()
}

const list_api = () => {
    if (typeof find_data.seats != 'number') {
        find_data.seats = ''
    }
    if (find_data.dataType == '1') {
        // let luser = JSON.parse(localStorage.getItem("luser"))
        // let luser_companyNum = luser.companyNum
        // find_data.companyNums = [luser_companyNum]
        // find_data.companyNums = find_data.companyNums.concat(companyNums.value)
        find_data.companyNums = companyNums.value
        carServiceList(find_data).then(res => {

            list24.value = getFilterData(res.data, 1, num_value.value);

            let num = (list24.value.length + 1) * 24
            height_num.value = num + 'px'

        })
    } else {
        carScheduleList(find_data).then(res => {
            let data = res.data

            list30.value = getFilterData(data, 2, 0);

        })
    }

}
//#endregion

const getFilterData = (list, type, day) => {
    if (type == 1) {


        // 1小时的宽度
        let hWidth = 0;


        // 最小偏移量
        let minLeft = 338;

        list.forEach((it, i) => {
            let os = it.orders;

            if (os) {// 存在车辆行程

                os.forEach(o => {
                    if (!o.stime || !o.etime) {

                    } else {
                        // 行程起止时间
                        let st = str2date(o.stime), et = str2date(o.etime);
                        // 当天起止时间
                        let cst = str2date(getSEToday(day)[0]), cet = str2date(getSEToday(day)[1]);

                        let h = 0;

                        // 计算左边偏移量
                        // if (st <= cst) {
                        //     // 行程开始时间小于或等于当天开始时间
                        //     o.left = `${minLeft+25}px`;

                        // } else {
                        //     // 获取开始时间距离当天开始时间多少小时
                        //     h = num((st.getTime() - cst.getTime()) / 1000 / 60 / 60, 4);
                        //     o.left = `calc(${hWidth}*${h} + ${minLeft}px)`;

                        // }
                        // 获取开始时间距离当天开始时间多少小时
                        h = num((st.getTime() - cst.getTime()) / 1000 / 60 / 60, 4);

                        let time1 = 24 * 60
                        let time11 = o.stime.split(' ')[1].split(':')[0] * 60 + Number(o.stime.split(' ')[1].split(':')[1])

                        //  let time2 = o.stime.split(' ')[1].split(':')[0]*60 *o.stime.split(' ')[1].split(':')[1]
                        //  let time3 = o.etime.split(' ')[1].split(':')[0]*60 *o.etime.split(' ')[1].split(':')[1]
                        // let time2 = Math.ceil(st.getTime() / 1000 /24/60/60) 
                        //  let time3 = Math.ceil(et.getTime() / 1000 /24/60/60);
                        let time2 = st.getTime() / 1000 / 24 / 60 / 60
                        let time3 = et.getTime() / 1000 / 24 / 60 / 60

                        let time_c = time11 / time1 * 1250

                        // let lett_num =(time_c *1273) + minLeft 
                        o.left = time_c + minLeft + 'px'
                        // 1605
                        // o.left = `calc(${hWidth}*${h} + ${minLeft}px)`;


                        // // 计算宽度（4种情况，起止时间在尾部交叉当天、起止时间在当天中、起止时间头部交叉当天）
                        // if (st < cst && et <= cet) {
                        //     // 行程开始时间 < 当天开始时间 && 行程结束时间 <= 当天结束时间

                        //     // 小时 = (行程结束时间 - 当天开始时间)/1000/60/60
                        //     h = num((et.getTime() - cst.getTime()) / 1000 / 60 / 60, 4);

                        // } else if (st >= cst && et > cet) {
                        //     // 行程开始时间 >= 当天开始时间 && 行程结束时间 > 当天结束时间

                        //     // 小时 = (行程结束时间 - 行程开始时间)/1000/60/60
                        //     h = num((cet.getTime() - st.getTime()) / 1000 / 60 / 60, 4);

                        // } else if (st >= cst && et <= cet) {
                        //     // 行程开始时间 >= 当天开始时间 && 行程结束时间 <= 当天结束时间

                        //     // 小时 = (当天结束时间 - 当天开始时间)/1000/60/60
                        //     h = num((et.getTime() - st.getTime()) / 1000 / 60 / 60, 4);

                        // } else {
                        //     // 行程开始时间 <= 当天开始时间 && 行程结束时间 >= 当天结束时间

                        //     // 小时 = (当天结束时间 - 当天开始时间)/1000/60/60
                        //     h = num((cet.getTime() - cst.getTime()) / 1000 / 60 / 60, 4);

                        // }
                        // h = num((et.getTime() - st.getTime()) / 1000 / 60 / 60, 4);

                        // o.width = `calc(${hWidth}*${h})`;
                        let width1 = 1350
                        let mat = Math.abs(time3 - time2)
                        let mar_num = mat * width1
                        // o.width = `calc((${time3}-${time2})*(${width1}))`;

                        o.width = mar_num + 'px';
                        // o.left = `calc(${hWidth}*(${time1}/${time2}) + ${minLeft}px)`;

                    }
                });
            }
        });
    } else if (type == 2) {
        list.forEach((it, i) => {
            let ds = it.carMap.dayList;

            it.carMap.ds = {};// 定义一个新对象
            ds.forEach(dit => {
                if (dit.other != 0) it.carMap.ds[dit.id] = dit.other;
            });
        });
    }


    return list;
}

const str2date = (dateStr) => {
    if (dateStr.indexOf('-') != -1) dateStr = dateStr.replace(/-/g, "/");
    return new Date(dateStr);

}

const getSEToday = (day) => {
    let todaytime = new Date().getTime();
    if (day && isPosOrNegInt(day)) {
        day = parseInt(day);
        if (day != 0) todaytime += day * 1000 * 60 * 60 * 24;
    }

    let date = date2str(new Date(todaytime), 'yyyy-MM-dd');
    return [`${date} 00:00:00`, `${date} 23:59:59`];
}

const date2str = (date, fmt) => {
    return datefmt(date, fmt);
}

const datefmt = (date, format = 'yyyy-MM-dd HH:mm') => {
    let fmt = format;

    // 传入的是时间字符串，则转换成时间类型
    if (typeof (date) === 'string') date = str2date(date);

    if (format.indexOf('-') != -1) format = format.replace(/-/g, '/');

    const pad = (n) => (n < 10 ? `0${n}` : n.toString());

    let res = format
        .replace('yyyy', date.getFullYear())
        .replace('MM', pad(date.getMonth() + 1))
        .replace('dd', pad(date.getDate()))
        .replace('HH', pad(date.getHours()))
        .replace('mm', pad(date.getMinutes()))
        .replace('ss', pad(date.getSeconds()));

    if (fmt.indexOf('-') != -1) res = res.replace(/\//g, '-');

    return res;
}

const isPosOrNegInt = (v) => {
    return matchReg(/^(((-)?\+?[1-9]\d*)|[0])$/, v);
}

const matchReg = (reg, v) => {
    if (!(reg.test(v))) {
        return false;
    } else {
        return true;
    }
}

const num = (val, len) => {
    if (!val) return 0;

    // 默认保留两位小数
    if (!len) len = 2;

    val = val + '';

    if (!isNumber(val)) {
        return val; // 不是数字，原字符返回
    } else if (val.indexOf('.') != -1) {
        // 存在小数点，判断小数点后面的位数，如果大于传入的长度，则截取
        let v = val.substr(val.indexOf('.') + 1);
        if (v.length > len) val = val.substr(0, val.indexOf('.') + len + 1);

        return parseFloat(val);
    } else {
        // 不存在小数点，转换成浮点数字返回
        return parseFloat(val);
    }
}

const isNumber = (v) => {
    return matchReg(/^[0-9]+.?[0-9]*$/, v);
}


//#region 搜索
const search_btn = () => {
    // localStorage.setItem('account_management', CircularJSON.stringify(find_data))
    list_api()
}
//#endregion


</script>

<style scoped lang='scss'>
.car-dynamic-list {


    .car-list {

        position: relative;

        ul:first-child {
            overflow-y: hidden !important;
            margin-right: 10px;

            // 第一行
            &:first-child {
                label {
                    border-top: 1px solid #1890ff;
                    border-bottom: 1px solid #1890ff;
                }

                label.lab-24:nth-child(n+3) {
                    u {
                        position: absolute;
                        top: -5px;
                        right: -7px;
                        text-decoration: none;
                    }
                }

                // 0点时样式
                label:nth-child(3) {
                    u {
                        right: -4px;
                    }
                }

                label.lab-30:nth-child(n+3) {
                    u {
                        position: absolute;
                        top: -5px;
                        right: 15px;
                        text-decoration: none;
                    }
                }
            }
        }

        ul {

            overflow-y: auto;
            overflow-x: hidden;
            margin: 0;
            padding: 0;

            li {
                list-style: none;
                height: 25px;
                position: relative;

                i {
                    position: absolute;
                    top: 0px;
                    height: 24px;
                    line-height: 24px;
                    font-style: normal;
                    display: inline-block;
                    text-align: left;
                    font-size: 12px;
                    text-decoration: none;
                    background: #1890ff;
                    color: #fff;

                    span {
                        cursor: default;
                        display: inline-block;
                        height: 100%;
                        width: 100%;

                        &:hover {
                            opacity: 0.7;
                        }
                    }
                }

                label {
                    position: relative;
                    font-size: 12px;
                    display: inline-block;
                    height: 25px;
                    line-height: 32px;
                    font-weight: normal;
                    text-align: center;
                    border-right: 1px solid #1890ff;
                    border-bottom: 1px solid #1890ff;
                }

                label:nth-child(1) {
                    width: 100px;
                    border-left: 1px solid #1890ff;
                    padding-left: 20px;
                    position: relative;
                }

                label:nth-child(2) {
                    width: 60px;
                }

                label:nth-child(3) {
                    width: 150px !important;
                    text-align: left;

                    span {
                        display: inline-block;
                        width: 100%;
                        overflow: hidden;
                        white-space: nowrap;
                        text-overflow: ellipsis;
                    }
                }

                label:nth-child(n-3) {
                    span {
                        position: absolute;
                        top: -3px;
                        left: 0px;
                    }
                }



                .lab-24 {
                    width: calc((100% - 380px)/24);
                }

                .lab-30 {
                    width: calc((100% - 380px)/30);
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;

                    span {
                        display: inline-block;
                        height: 100%;
                        width: 100%;
                        overflow: hidden;
                        white-space: nowrap;
                        text-overflow: ellipsis;
                    }
                }
            }
        }
    }

}

.hovercss :hover {
    background-color: #ddd;
}
</style>

<style>
.route-tips {
    max-width: 500px !important;
}

.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}


.el-table .el-table__cell {
    padding: 0px !important;
}
</style>
